// DOM元素
const loginBtn = document.getElementById('loginBtn');
const logoutBtn = document.getElementById('logoutBtn');
const loginStatus = document.getElementById('loginStatus');
const loginModal = document.getElementById('loginModal');
const loginForm = document.getElementById('loginForm');
const cancelLoginBtn = document.getElementById('cancelLoginBtn');
const createAppBtn = document.getElementById('createAppBtn');
const createAppModal = document.getElementById('createAppModal');
const createAppForm = document.getElementById('createAppForm');
const cancelCreateBtn = document.getElementById('cancelCreateBtn');
const searchInput = document.getElementById('searchInput');
const appsList = document.getElementById('appsList');
const statusMessage = document.getElementById('statusMessage');

let currentDirectory = '';
let apps = [];
let currentFile = 'template';

// 检查登录状态
async function checkLoginStatus() {
    try {
        const response = await fetch('/api/check-login');
        const data = await response.json();
        if (data.success) {
            updateLoginUI(true);
        } else {
            updateLoginUI(false);
        }
    } catch (error) {
        updateLoginUI(false);
    }
}

// 更新登录UI
function updateLoginUI(isLoggedIn) {
    if (isLoggedIn) {
        loginStatus.textContent = '已登录';
        loginBtn.style.display = 'none';
        logoutBtn.style.display = 'inline-block';
    } else {
        loginStatus.textContent = '未登录';
        loginBtn.style.display = 'inline-block';
    }
}

// 加载应用列表
async function loadApps() {
    try {
        const response = await fetch('/api/apps');
        const data = await response.json();
        if (data.success) {
            apps = data.apps;
            renderApps(apps);
        } else {
            showStatus(data.error, 'error');
        }
    } catch (error) {
        showStatus('加载应用列表失败', 'error');
    }
}

// 渲染应用列表
function renderApps(appsToRender) {
    appsList.innerHTML = '';
    appsToRender.forEach(app => {
        const appCard = document.createElement('div');
        appCard.className = 'app-card';
        appCard.innerHTML = `
            <h3>${app.name}</h3>
            <div class="app-info">
                <p class="app-project">项目: ${app.projectName || '未设置'}</p>
                <p class="app-description">${app.description || '暂无描述'}</p>
                <div class="app-meta">
                    <span class="app-version">版本: ${app.version || '0.1.0'}</span>
                    <span class="app-author">作者: ${app.author || '未知'}</span>
                </div>
            </div>
            <div class="app-actions">
                <button onclick="editApp('${app.id}')" class="edit-btn">编辑</button>
                <button onclick="packageApp('${app.id}')">打包</button>
                <button onclick="publishApp('${app.id}')">发布</button>
                <button onclick="removeApp('${app.id}')">移除</button>
                <button onclick="deleteApp('${app.id}')" class="delete-btn">删除</button>
            </div>
        `;
        appsList.appendChild(appCard);
    });
}

// 加载文件系统
async function loadFileSystem(dirPath = '') {
    try {
        // 将路径中的反斜杠替换为正斜杠，并确保路径正确编码
        const encodedPath = dirPath.replace(/\\/g, '/');
        const response = await fetch(`/api/filesystem?path=${encodeURIComponent(encodedPath)}`);
        const data = await response.json();
        if (data.success) {
            currentDirectory = data.files.currentPath;
            currentPathSpan.textContent = currentDirectory || '/';
            renderFileSystem(data.files);
        } else {
            showStatus(data.error, 'error');
        }
    } catch (error) {
        showStatus('加载文件系统失败', 'error');
    }
}

// 渲染文件系统
function renderFileSystem(files) {
    currentPathSpan.textContent = files.currentPath || '/';
    fileList.innerHTML = `
        ${files.parentPath !== '' ? `
            <div class="file-item" onclick="loadFileSystem('${files.parentPath.replace(/\\/g, '/')}')">
                <span class="file-icon">📁</span>
                <span class="file-name">..</span>
            </div>
        ` : ''}
        ${files.files.map(file => `
            <div class="file-item" onclick="${file.isDirectory ? `loadFileSystem('${file.path.replace(/\\/g, '/')}')` : ''}">
                <span class="file-icon">${file.isDirectory ? '📁' : '📄'}</span>
                <span class="file-name">${file.name}</span>
            </div>
        `).join('')}
    `;
}

// 搜索应用
searchInput.addEventListener('input', (e) => {
    const searchTerm = e.target.value.toLowerCase();
    const filteredApps = apps.filter(app =>
        app.name.toLowerCase().includes(searchTerm) ||
        (app.description && app.description.toLowerCase().includes(searchTerm))
    );
    renderApps(filteredApps);
});

// 显示创建应用模态框
createAppBtn.addEventListener('click', () => {
    createAppModal.style.display = 'block';
    loadTemplates();
});

cancelCreateBtn.addEventListener('click', () => {
    closeCreateAppModal();
});

// 关闭创建应用模态框
function closeCreateAppModal() {
    createAppModal.style.display = 'none';
    createAppForm.reset();
}

// 浏览位置
browseLocationBtn.addEventListener('click', () => {
    fileBrowserModal.style.display = 'block';
    loadFileSystem();
});

// 取消浏览位置
cancelBrowseBtn.addEventListener('click', () => {
    fileBrowserModal.style.display = 'none';
});

// 返回上级目录
backToParentBtn.addEventListener('click', () => {
    if (currentDirectory) {
        const parentPath = currentDirectory.split('/').slice(0, -1).join('/');
        loadFileSystem(parentPath);
    }
});

// 选择位置
selectLocationBtn.addEventListener('click', () => {
    appLocationInput.value = currentDirectory;
    fileBrowserModal.style.display = 'none';
});

// 加载模板列表
async function loadTemplates() {
    try {
        const response = await fetch('/api/templates');
        const data = await response.json();
        if (data.success) {
            const templateSelect = document.getElementById('appTemplate');
            templateSelect.innerHTML = data.templates.map(template => `
                <option value="${template.id}">${template.name}</option>
            `).join('');
        } else {
            showStatus(data.error, 'error');
        }
    } catch (error) {
        showStatus('加载模板列表失败', 'error');
    }
}

// 创建应用
createAppForm.addEventListener('submit', async (e) => {
    e.preventDefault();
    const name = document.getElementById('appName').value;
    const projectName = document.getElementById('projectName').value;
    const description = document.getElementById('appDescription').value;
    const version = document.getElementById('appVersion').value;
    const author = document.getElementById('appAuthor').value;
    const location = appLocationInput.value;
    const template = document.getElementById('appTemplate').value;

    try {
        const response = await fetch('/api/create-app', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                name,
                projectName,
                description,
                version,
                author,
                location,
                template
            })
        });

        const data = await response.json();
        if (data.success) {
            showStatus('应用创建成功', 'success');
            createAppModal.style.display = 'none';
            createAppForm.reset();
            loadApps();
        } else {
            showStatus(data.error, 'error');
        }
    } catch (error) {
        showStatus('创建应用失败', 'error');
    }
});

// 打包应用
async function packageApp(id) {
    try {
        const response = await fetch('/api/build-app', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ id })
        });

        const data = await response.json();
        if (data.success) {
            showStatus('应用打包成功', 'success');
        } else {
            showStatus(data.error, 'error');
        }
    } catch (error) {
        showStatus('打包应用失败', 'error');
    }
}

// 发布应用
async function publishApp(id) {
    try {
        const response = await fetch('/api/publish-app', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ id })
        });

        const data = await response.json();
        if (data.success) {
            showStatus('应用发布成功', 'success');
        } else {
            showStatus(data.error, 'error');
        }
    } catch (error) {
        showStatus('发布应用失败', 'error');
    }
}

// 移除应用
async function removeApp(id) {
    if (!confirm(`确定要移除应用吗？`)) return;

    try {
        const response = await fetch(`/api/apps/${id}/remove`, {
            method: 'POST'
        });

        const data = await response.json();
        if (data.success) {
            showStatus('应用移除成功', 'success');
            loadApps();
        } else {
            showStatus(data.error, 'error');
        }
    } catch (error) {
        showStatus('移除应用失败', 'error');
    }
}

// 删除应用
async function deleteApp(id) {
    if (!confirm(`确定要删除应用吗？此操作不可恢复！`)) return;

    try {
        const response = await fetch(`/api/apps/${id}`, {
            method: 'DELETE'
        });

        const data = await response.json();
        if (data.success) {
            showStatus('应用删除成功', 'success');
            loadApps();
        } else {
            showStatus(data.error, 'error');
        }
    } catch (error) {
        showStatus('删除应用失败', 'error');
    }
}

// 显示登录模态框
loginBtn.addEventListener('click', () => {
    loginModal.style.display = 'block';
});

// 关闭登录模态框
cancelLoginBtn.addEventListener('click', () => {
    loginModal.style.display = 'none';
    loginForm.reset();
});

// 处理登录
loginForm.addEventListener('submit', async (e) => {
    e.preventDefault();
    const username = document.getElementById('username').value;
    const password = document.getElementById('password').value;

    try {
        const response = await fetch('/api/login', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ username, password })
        });

        const data = await response.json();
        if (data.success) {
            showStatus('登录成功', 'success');
            loginModal.style.display = 'none';
            loginForm.reset();
            updateLoginUI(true);
            loadApps();
        } else {
            showStatus(data.error || '登录失败', 'error');
        }
    } catch (error) {
        showStatus('登录失败', 'error');
    }
});

// 处理退出
logoutBtn.addEventListener('click', async () => {
    try {
        const response = await fetch('/api/logout', {
            method: 'POST'
        });

        const data = await response.json();
        if (data.success) {
            showStatus('已退出登录', 'success');
            updateLoginUI(false);
            appsList.innerHTML = '';
        } else {
            showStatus(data.error || '退出失败', 'error');
        }
    } catch (error) {
        showStatus('退出失败', 'error');
    }
});

// 点击模态框外部关闭
window.addEventListener('click', (e) => {
    if (e.target === loginModal) {
        loginModal.style.display = 'none';
        loginForm.reset();
    }
    if (e.target === createAppModal) {
        closeCreateAppModal();
    }
    if (e.target === fileBrowserModal) {
        fileBrowserModal.style.display = 'none';
    }
});

// 显示状态消息
function showStatus(message, type = 'info') {
    statusMessage.textContent = message;
    statusMessage.className = `status-message ${type}`;
    setTimeout(() => {
        statusMessage.className = 'status-message';
    }, 3000);
}

// 编辑应用
function editApp(id) {
    // 打开新的编辑器页面
    window.open(`/editor.html?id=${id}`, '_blank');
}

// 初始化
document.addEventListener('DOMContentLoaded', () => {
    checkLoginStatus();
    loadApps();
    loadTemplates();
});
